/**
 * 最少使用算法
 */
class LRUCache {
  constructor(limit) {
    this.limit = limit || 10;
    this.cacheKey = [];
    this.cacheMap = new Map();
  }

  put(key, value) {
    // 缓存满了，需要淘汰末尾的
    if(this.cacheKey.length >= this.limit) {
      let deleteKey = this.cacheKey.pop();
      this.cacheMap.delete(deleteKey);
    }
    if(this.cacheMap.has(key)) {
      this.cacheMap.set(key, value);
    } else {
      this.cacheKey.push(key);
      this.cacheMap.set(key, value);
    }
  }
  
  get(key) {
    if(this.cacheMap.has(key)) {
      // 把访问挪到第一位来
      let index = this.cacheKey.indexOf(key);
      this.cacheKey.splice(index, 1);
      this.cacheKey.unshift(key);
      return this.cacheMap.get(key);
    }
    return -1;
  }
}

let lru = new LRUCache(2);

lru.put(1, 1);
lru.put(2, 2);
// lru.put(3, 3);

console.log(lru.get(1));
console.log(lru.get(2));
lru.put(3, 3);
console.log(lru.get(1))
console.log(lru.get(3))
console.log(lru.get(2))